import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Table, Button, Input, Grid, Form, Select, Message, Dialog } from '@alifd/next';
import '#/scss/Global.scss';
import { ApiOfPolicyBindLinkages } from '#/utils/policyApiDefine';
import Device from '#/pages/Device';
import EditLinkageMetric from './EditLinkageMetric'

const { Row, Col } = Grid;

export default class BindLinkage extends Component {
    static displayName = 'BindLinkage';
    static propTypes = {};
    static defaultProps = {};

    constructor(props) {
        super(props);
        let editInstance = this.props.editInstance;
        this.state = {
            policyCode: editInstance.code,
            availableResources: [],
            reboundResources: editInstance.policyRefLinkages,
            selectDialogVisible: false,
            editMetricDialogVisible: false,
        };
    }


    renderOper = (value, index, item) => {
        let that = this;
        return (
            <div>
                <Button onClick={() => this.onEdit(item)} type="primary" text >编辑</Button>
                <Button onClick={() => this.onRemove(item)} type="primary" text style={{ color: '#ff3000', marginLeft: '10px' }}>{item.dirty == 1 ? '撤销' : '移除'}</Button>
            </div>
        );
    }

    // dirty undefined/-1/0:无操作 1:准备移除 2：新添加
    onRemove = resource => {
        let reboundResources = this.state.reboundResources;
        let _resource = reboundResources.find(item => item.resourceCode === resource.resourceCode);
        if (_resource.dirty == 2) {
            reboundResources.splice(reboundResources.findIndex(item => item.resourceCode === _resource.resourceCode), 1)
        } else if (_resource.dirty == 1) {
            delete _resource.dirty;
        } else {
            _resource.dirty = 1;
        }
        this.setState({ reboundResources })
    }

    onEdit = resource => {
        console.log(resource)
        this.setState({
            resourceInstance: resource,
            editMetricDialogVisible: true,
        })
    }

    onBind = () => {
        let that = this;
        let reboundResources = this.state.reboundResources.filter(item => item.dirty != 1);
        ApiOfPolicyBindLinkages(this.state.policyCode, reboundResources)
            .then(() => that.props.submitCallback('success'))
    }

    onOpenSelectDialog = () => {
        this.setState({
            selectDialogVisible: true,
        });
    }


    onCloseSelectDialog = items => {
        let that = this;
        this.setState({
            selectDialogVisible: false
        });
        if (!Array.isArray(items)) return;
        items.forEach(item => {
            let index = that.state.reboundResources.findIndex(value => value.resourceCode == item.code);
            if (index == -1) {
                item.dirty = 2;// 标记为准备新加
                item.resourceCode = item.code;
                that.state.reboundResources.push(item);
                that.setState({ reboundResources: that.state.reboundResources })
            }
        })
    }

    onCloseEditMetricDialog = (controlUsageMetrics, cancelUsageMetrics) => {
        if("closeClick" != controlUsageMetrics) {
          this.state.resourceInstance.controlUsageMetrics = controlUsageMetrics
          this.state.resourceInstance.cancelUsageMetrics = cancelUsageMetrics
        }
       
        this.setState({
            editMetricDialogVisible: false
        });
    }

    setRowProps = (item, index) => {
        if (item.dirty === 1) {
            return {
                style: styles.willRemove,
            };
        } else if (item.dirty === 2) {
            return {
                style: styles.willAdd,
            };
        }
    }

    renderSummery = () => {
        let willAddCount = this.state.reboundResources.filter(item => item.dirty != 1).length;
        let willRemoveCount = this.state.reboundResources.length - willAddCount;
        let text = '待绑定：' + willAddCount + ' 个，' + '待移除：' + willRemoveCount + ' 个';
        return (
            <span>
                {text}
            </span>
        )
    }

    render() {
        let summery = this.renderSummery();
        let Operation = <Row wrap gutter="20">
            <Col l="6">
                <div style={{ ...styles.formItem, fontSize: '14px' }}>
                    {summery}
                </div>
            </Col>
            <Col l="6" offset="12">
                <div style={styles.formItemRight}>
                    <Button onClick={this.onOpenSelectDialog.bind(this)} size="medium"> 选择更多 </Button>
                    <Button onClick={this.onBind} type="primary" size="medium" style={{ marginLeft: 20 }} >提 交 </Button>
                </div>
            </Col>
        </Row>;

        return (
            <IceContainer style={styles.container}>
                {Operation}
                <Table
                    dataSource={this.state.reboundResources}
                    hasBorder={false}
                    getRowProps={this.setRowProps}
                    style={{ padding: '0 20px 20px' }}
                >
                    <Table.Column width={150} title="资源编码" dataIndex="resourceCode" />
                    <Table.Column title="控制指标" dataIndex="controlUsageMetrics" />
                    <Table.Column title="解除指标" dataIndex="cancelUsageMetrics" />
                    <Table.Column
                        width={100}
                        title="操作"
                        cell={this.renderOper}
                    />
                </Table>
                {Operation}
                <Dialog
                    className="dialog-with-table"
                    style={{ width: '80%' }}
                    title="选择资源"
                    visible={this.state.selectDialogVisible}
                    footer={false}
                    shouldUpdatePosition={true}
                    onClose={this.onCloseSelectDialog}>
                    <Device forSelectUsage={true} match={this.props.match} onSelect={this.onCloseSelectDialog} />
                </Dialog>
                <Dialog
                  className="dialog-with-table"
                  style={{ width: '60%' }}
                  title="选择指标"
                  visible={this.state.editMetricDialogVisible}
                  footer={false}
                  onClose={this.onCloseEditMetricDialog}>
                  <EditLinkageMetric resourceInstance={this.state.resourceInstance} submitCallback={this.onCloseEditMetricDialog} />
                </Dialog>
            </IceContainer>
        );
    }
}

const styles = {
    container: {
        margin: '20px',
        padding: '0 0 20px',
    },
    title: {
        margin: '0',
        padding: '15px 20px',
        fonSize: '16px',
        textOverflow: 'ellipsis',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        color: 'rgba(0,0,0,.85)',
        fontWeight: '500',
        borderBottom: '1px solid #eee',
    },
    link: {
        margin: '0 5px',
        color: 'rgba(49, 128, 253, 0.65)',
        cursor: 'pointer',
        textDecoration: 'none',
    },
    separator: {
        margin: '0 3px',
        display: 'inline-block',
        height: '12px',
        width: '1px',
        verticalAlign: 'middle',
        background: '#e8e8e8',
    },
    pagination: {
        textAlign: 'right',
        marginRight: '20px',
    },
    editIcon: {
        color: '#2874D1',
        cursor: 'pointer',
    },
    horizontal: {
        dl: {
            marginTop: '3px',
            marginBottom: '3px',
        },
        dt: {
            float: 'left',
            width: '80px',
            overflow: 'hidden',
            clear: 'left',
            textAlign: 'right',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
        },
        dd: {
            marginLeft: '100px',
        }
    },
    formItem: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
    },
    formItemRight: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
        float: 'right'
    },
    formComponent: {
        minWidth: '300px',
    },
    formLabel: {
        minWidth: '70px',
    },
    willAdd: {
        background: '#dff0d8'
    },
    willRemove: {
        background: '#f2dede'
    },
};